const express = require("express");
const fs = require("fs");
const path = require("path");
const formidable = require("formidable");
// const { promisify } = require("util");

const router = express.Router();
const app = require("../middlewares");
const db = require("../database");

router.get("/ceshi", (req, res) => {
  res.json({ success: true, message: "接口测试" });
});
// const copyFileAsync = promisify(fs.copyFile);
// const unlinkAsync = promisify(fs.unlink);
// const statAsync = promisify(fs.stat);
router.post("/upload", async (req, res, next) => {
  try {
    const form = new formidable.IncomingForm();
    const data = await parseFormAsync(form, req);
    const uploadedFiles = data.files.file; //返回数组
    if (!uploadedFiles || uploadedFiles.length === 0) {
      return res.status(400).json({ error: "没有上传文件" });
    }
    // 假设只处理第一个文件
    const uploadedFile = uploadedFiles[0];
    const { fileName } = data.fields;
    if (!uploadedFile || !uploadedFile.filepath) {
      return res.status(400).json({ error: "文件信息不完整" });
    }
    const filePath = uploadedFile.filepath;
    const originalFileName = uploadedFile.originalFilename;
    const fileExtension = path.extname(originalFileName);
    const newFileName = fileName
      ? fileName + fileExtension
      : "default" + fileExtension;
    const a = process.cwd();
    const newPath = path.join(a, "uploads", newFileName);
    await moveAndDeleteFileAsync(filePath, newPath);
    res.json({ message: "文件上传成功" });
  } catch (error) {
    next(error);
  }
});

// 异步解析表单数据
function parseFormAsync(form, req) {
  return new Promise((resolve, reject) => {
    form.parse(req, (err, fields, files) => {
      if (err) {
        reject(err);
      } else {
        resolve({ fields, files });
      }
    });
  });
}

// 异步移动和删除文件
function moveAndDeleteFileAsync(sourcePath, destPath) {
  return new Promise((resolve, reject) => {
    fs.copyFile(sourcePath, destPath, (copyErr) => {
      if (copyErr) {
        reject(copyErr);
      } else {
        fs.unlink(sourcePath, (unlinkErr) => {
          if (unlinkErr) {
            reject(unlinkErr);
          } else {
            resolve();
          }
        });
      }
    });
  });
}

// 判断文件是否为空
function isFileEmpty(filePath) {
  try {
    const stats = fs.statSync(filePath);
    return stats.size === 0;
  } catch (error) {
    console.error("获取文件状态信息失败:", error);
    return true;
  }
}

// 插入数据接口
router.post("/pushItem", (req, res) => {
  const jsonData = req.body;
  if (!jsonData) {
    return res.status(500).json({ success: false, error: "参数传递错误" });
  }
  // 异步执行插入数据
  db.serialize(() => {
    db.run(
      "INSERT INTO item_list (json_data) VALUES (?)",
      JSON.stringify(jsonData),
      function (err) {
        if (err) {
          console.error(err);
          return res.status(500).json({ success: false, error: "添加失败" });
        }
        res.json({
          success: true,
          message: "添加成功",
          insertedId: this.lastID,
        });
      }
    );
  });
});

// 查询所有数据
router.post("/getAll", (req, res) => {
  db.all("SELECT * FROM item_list", [], function (err, rows) {
    if (err) {
      return res.status(500).json({ error: "查询失败" });
    } else {
      const parsedRows = rows.map((row) => ({
        id: row.id,
        json_data: JSON.parse(row.json_data),
      }));
      res.status(200).json({ ode: 200,success: true, message: "查询成功",data: parsedRows })
    }
  });
});

// 通过id查询单个记录接口
router.get("/getDataById", (req, res) => {
  const id = req.query.id;
  if (!id) {
    return res.status(500).json({ success: false, error: "参数传递错误" });
  }
  db.get("SELECT * FROM item_list WHERE id = ?", [id], function (err, row) {
    if (err) {
      console.error(err);
      return res.status(500).json({ success: false, error: "查询错误" });
    }
    if (!row) {
      return res.status(404).json({ success: false, error: "没有查询的信息" });
    }
    res.status(200).json({
      success: true,
      data: {
        id: row.id,
        json_data: JSON.parse(row.json_data),
      },
      message: "查询成功",
    });
  });
});

// 修改 json_data 接口
router.post("/updateData", (req, res) => {
  const id = req.body.data.id;
  const json_data = req.body.data.json_data;
  if (!(id && json_data)) {
    return res.status(500).json({ success: false, error: "参数传递错误" });
  }
  // 异步执行更新数据
  db.serialize(() => {
    db.run(
      "UPDATE item_list SET json_data = ? WHERE id = ?",
      [JSON.stringify(json_data), id],
      function (err) {
        if (err) {
          console.error(err);
          return res.status(500).json({ success: false, error: "修改失败" });
        }
        res.status(200).json({ success: true, message: "修改成功" });
      }
    );
  });
});

//通过id删除一条
// 根据 ID 删除记录接口
router.delete("/deleteRecord", (req, res) => {
  const id = req.query.id;
  // 异步执行删除数据
  db.serialize(() => {
    db.run("DELETE FROM item_list WHERE id = ?", [id], function (err) {
      if (err) {
        console.error(err);
        return res.status(500).json({ success: false, error: "删除失败" });
      }
      res.status(200).json({ success: true, message: "删除成功" });
    });
  });
});

module.exports = router;
